package com.example.pclimb.repository;

import android.app.Application;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.pclimb.dao.UserDao;
import com.example.pclimb.database.PclimbDatabase;
import com.example.pclimb.model.User;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户数据仓库，处理用户相关的所有数据操作
 */
public class UserRepository {
    private UserDao userDao;
    private LiveData<List<User>> allApprovedGuides;
    private LiveData<List<User>> pendingGuideApplications;
    private ExecutorService executorService;

    public UserRepository(Application application) {
        PclimbDatabase database = PclimbDatabase.getInstance(application);
        userDao = database.userDao();
        allApprovedGuides = userDao.getAllApprovedGuides();
        pendingGuideApplications = userDao.getPendingGuideApplications();
        executorService = Executors.newSingleThreadExecutor();
    }

    // 插入用户
    public void insert(User user, Callback<Long> callback) {
        executorService.execute(() -> {
            long id = userDao.insert(user);
            callback.onResult(id);
        });
    }

    // 更新用户
    public void update(User user) {
        executorService.execute(() -> {
            userDao.update(user);
        });
    }

    // 删除用户
    public void delete(User user) {
        executorService.execute(() -> {
            userDao.delete(user);
        });
    }

    // 登录
    public LiveData<User> login(String username, String password) {
        return userDao.login(username, password);
    }

    // 获取所有通过认证的陪爬人员
    public LiveData<List<User>> getAllApprovedGuides() {
        return allApprovedGuides;
    }

    // 获取待审核的陪爬申请
    public LiveData<List<User>> getPendingGuideApplications() {
        return pendingGuideApplications;
    }

    // 获取用户信息
    public LiveData<User> getUserById(int userId) {
        return userDao.getUserById(userId);
    }

    // 根据用户名获取用户
    public LiveData<User> getUserByUsername(String username) {
        return userDao.getUserByUsername(username);
    }

    // 批准陪爬申请
    public void approveGuideApplication(int userId) {
        executorService.execute(() -> {
            userDao.approveGuideApplication(userId);
        });
    }

    // 拒绝陪爬申请
    public void rejectGuideApplication(int userId) {
        executorService.execute(() -> {
            userDao.rejectGuideApplication(userId);
        });
    }

    // 更新用户评分
    public void updateRating(int userId, float newRating) {
        executorService.execute(() -> {
            userDao.updateRating(userId, newRating);
        });
    }

    /**
     * 根据申请状态获取用户
     */
    public LiveData<List<User>> getUsersByApplicationStatus(int applicationStatus) {
        return userDao.getUsersByApplicationStatus(applicationStatus);
    }

    // 回调接口
    public interface Callback<T> {
        void onResult(T result);
    }
} 